package com.richman.view;



import javax.swing.JPanel;
import javax.swing.JPopupMenu;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

import com.richman.controller.DecreaseRatioClient;
import com.richman.ps38.entity.BetAdyData;
import com.richman.ps38.entity.BetDvalue;
import com.richman.ps38.entity.Event;
import com.richman.ps38.entity.HGEvent;
import com.richman.utils.Common;
import com.richman.utils.GameTimeAsc;
import com.richman.view.BetLogPane;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class BetAlreadyPane extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8L;
	
	private  Vector<String[]> detailsData = new Vector<String[]>();
	
	public Vector<Event> gameDetailsVec = new Vector<Event>(); 
	
	
	public RebetWindow rebetWnd = new RebetWindow();
	
	//BrowserPanel bp = new BrowserPanel();
	
	private JPopupMenu m_tablepopupMenu;

    
    JMenuItem rebetMenuItem = null;
    
	public int selectedRow = -1;
	
	
	MyTableModel tableMode = new MyTableModel();
	
	private  ReadWriteLock betDvaluesLock = new ReentrantReadWriteLock(); 

	Vector<BetAdyData> gamedetailsLocal = new Vector<BetAdyData>();
	
	private  ReadWriteLock gamedetailsLock = new ReentrantReadWriteLock(); 
	
	
	JTable table = null;

	/**
	 * Create the panel.
	 */
	public BetAlreadyPane() {
		setLayout(new BorderLayout(0, 0));

		JPanel funBtnPane = new JPanel();
		
		JButton cleanButton = new JButton("清空数据");
		cleanButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				int n = JOptionPane.showConfirmDialog(null, "确认要清空数据吗?", "清空数据",
						JOptionPane.YES_NO_OPTION);
				if (n == JOptionPane.YES_OPTION && DecreaseRatioClient.betCtrMng != null) {
					DecreaseRatioClient.betCtrMng.clearBetAdyData();
				}
				
			}
		});
		
		cleanButton.setBounds(20, 10, 60, 20);
		
		funBtnPane.add(cleanButton);
		
		add(funBtnPane, BorderLayout.NORTH);
		
		
	    table = new JTable(tableMode);

	    table.getColumnModel().getColumn(2).setPreferredWidth(250);

	    
	   
	    
	    table.setRowHeight(30);
	    
	    table.setFont(new java.awt.Font("黑体", Font.PLAIN, 15));
		
		
		JScrollPane scrollPane = new JScrollPane(table);
		add(scrollPane, BorderLayout.CENTER);

		table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
     	       //判断是否为鼠标的BUTTON3按钮，BUTTON3为鼠标右键  
     	       if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
     	          
     	    	 
     	    	   
     	           //弹出菜单  
     	         selectedRow = table.rowAtPoint(evt.getPoint());
     	           
     	         if(selectedRow == -1) {
     	        	 return;
     	         }
     	         
     	         
     	         String ps38betres = detailsData.elementAt(selectedRow)[13];
     	         
     	         if(ps38betres.contains("失败")) {
     	        	m_tablepopupMenu.show(table, evt.getX(), evt.getY());
     	         }

     	       }
            }  
        });
		
		

		
		
	    m_tablepopupMenu = new JPopupMenu();
	    rebetMenuItem = new JMenuItem();
	    rebetMenuItem.setText("手动补单");
	    rebetMenuItem.addActionListener(new java.awt.event.ActionListener() {  
            public void actionPerformed(java.awt.event.ActionEvent evt) {  
                //该操作需要做的事  
            	
            	try{
            		
            		boolean delSuc = false;
            		
            		rebetWnd.setgame(detailsData.elementAt(selectedRow));
            		
            		rebetWnd.setVisible(true);

            		if(delSuc == true) {
            			JOptionPane.showMessageDialog(null, "已解除匹配", "已解除匹配", JOptionPane.DEFAULT_OPTION);
            		}

            	}catch(Exception e){
            		e.printStackTrace();
            	}

            }  
        });
		

		
	    m_tablepopupMenu.add(rebetMenuItem);

	}
	
	
	
	public void updateBetAdyTable(Vector<String[]> gamedetails){
		
		try{


			if(gamedetails==null) {
				return;
			}
			
			if(detailsData.size() != 0){
				detailsData.clear();
			}
			
			for(int i = 0; i < gamedetails.size(); i++) {
				
				String[] game = gamedetails.elementAt(i);
				
				String[] numbers = game[2].split(",");
				String numberStr = "<html>";
				for(int j = 0; j < numbers.length;	j++) {
					if(numbers[j].equals(game[3])) {
						numbers[j] = "<font color='red'>" + numbers[j] + "</font>";
					}
				}
				String strtmp = "";
				for(int j = 0; j < numbers.length;	j++) {
					if(j==0) {
						strtmp = "<html>" + numbers[j];
					}else {
						strtmp = strtmp + "," +  numbers[j];
					}					
				}

				String[] item = {Integer.toString(i+1), game[0],game[1],strtmp,game[3]};
				
				detailsData.add(item);
				
			}
			
			setOneRowBackgroundColor();
			
			tableMode.updateTable();

			
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	
	
	
	
	
	
	
	
	
	
	public Vector<BetDvalue> getBetDvalus(){
		Vector<BetDvalue> vec = new Vector<BetDvalue>();
		
		betDvaluesLock.readLock().lock();
		
		
		
		for(int i = 0; i < DecreaseRatioClient.betCtrMng.betDvalues.size(); i++){
		
			
			
			
			vec.add(DecreaseRatioClient.betCtrMng.betDvalues.elementAt(i));
			

			
		}
		
		betDvaluesLock.readLock().unlock();
		
		return vec;
	}
	
	
	public Vector<BetAdyData> getBetAdyDatas(){
		
		Vector<BetAdyData> vec = new Vector<BetAdyData>();
		gamedetailsLock.readLock().lock();
		for(int i = 0; i < gamedetailsLocal.size(); i++){
			vec.add(gamedetailsLocal.elementAt(i));
		}		
		gamedetailsLock.readLock().unlock();		
		return vec;
	}
	
	
	
	
    public void setOneRowBackgroundColor() {
    	

    	
        try {  
        	
            DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
            	
            	
  
                public Component getTableCellRendererComponent(JTable table,  
                        Object value, boolean isSelected, boolean hasFocus,  
                        int row, int column) {  

                	
                    if (row%2==1) {  
                    	setBackground(new Color(246,246,246));  
                        
                    }else{  
                        setBackground(new Color(222,222,243));  
                    	//setBackground(new Color(1,1,1));  
                      
                    }  
                    
                    setHorizontalAlignment(JLabel.CENTER);
  
                    return super.getTableCellRendererComponent(table, value,  
                            isSelected, hasFocus, row, column);  
                }  
            };  
            
            
            DefaultTableCellRenderer resRender = new DefaultTableCellRenderer() {   

                public void setValue(Object value) { //重写setValue方法，从而可以动态设置列单元字体颜色   

                   
                	String str = value.toString();
                	
    				
    				
    				if(str.contains("成功")){
    					
    					setBackground(Color.GREEN);

    				}else if(str.contains("失败")){    	
    					setBackground(Color.red);
    				}else {
    					setBackground(Color.yellow);
    				}
    				
    				
    				setForeground(Color.BLACK);
    					
    				setText((value == null) ? "" : str);
    				
    				 setHorizontalAlignment(JLabel.CENTER);

                }   

            };
            
            
            
            
            
            DefaultTableCellRenderer ratioRender = new DefaultTableCellRenderer() {   

                public void setValue(Object value) { //重写setValue方法，从而可以动态设置列单元字体颜色   

                   
                	String str = value.toString();
                	
                	
                	setForeground(Color.BLACK);
                	
    				if(Common.isNum(str)) {
    					double ratio = Double.parseDouble(str);
    					if(ratio - DecreaseRatioClient.mainWnd.getbetodd() < 0.0) {
    						setForeground(Color.red);
    	    				
    					}
    				}
    				
    				//setBackground(new Color(246,246,246)); 
    				
    				
    					
    				setText((value == null) ? "" : str);
    				
    				 setHorizontalAlignment(JLabel.CENTER);

                } 
                
                
                public Component getTableCellRendererComponent(JTable table,  
                        Object value, boolean isSelected, boolean hasFocus,  
                        int row, int column) {  

                	
                    if (row%2==1) {  
                    	setBackground(new Color(246,246,246));  
                        
                    }else{  
                        setBackground(new Color(222,222,243));  
                    	//setBackground(new Color(1,1,1));  
                      
                    }  
                    
                    setHorizontalAlignment(JLabel.CENTER);
  
                    return super.getTableCellRendererComponent(table, value,  
                            isSelected, hasFocus, row, column);  
                }  
                
                
                

            }; 
            
            
            
            
            
            
            
            int columnCount = table.getColumnCount();  
            for (int i = 0; i < columnCount; i++) {  
            	
            	String columnname = table.getColumnName(i);
            	
            	if(columnname.equals("皇冠结果") || columnname.equals("结果")) {
            		table.getColumn(columnname).setCellRenderer(resRender);
            	//	continue;
            	}else if(columnname.equals("合并赔率")){
            		table.getColumn(columnname).setCellRenderer(ratioRender);
            		
            	}else {
            		table.getColumn(columnname).setCellRenderer(tcr);
            	}
            	
            	
            }  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
    
    }  
	
	
	
	

    public class MyTableModel extends AbstractTableModel  
    {  
        /**
		 * 
		 */
		private static final long serialVersionUID = 10086L;
		/* 
         * 这里和刚才一样，定义列名和每个数据的值 
         */  
        String[] columnNames =          
        	{ "序号", "期数", "时间", "降水号码", "开奖结果"};

  
        /** 
         * 构造方法，初始化二维数组data对应的数据 
         */  
        public MyTableModel()  
        {  

        }  
  
        // 以下为继承自AbstractTableModle的方法，可以自定义  
        /** 
         * 得到列名 
         */  
        @Override  
        public String getColumnName(int column)  
        {  
            return columnNames[column];  
        }  
          
        /** 
         * 重写方法，得到表格列数 
         */  
        @Override  
        public int getColumnCount()  
        {  
            return columnNames.length;  
        }  
  
        /** 
         * 得到表格行数 
         */  
        @Override  
        public int getRowCount()  
        {         
	        if(null == detailsData){
	    		return 0;
	    	}
            return detailsData.size();  
        }  
  
        /** 
         * 得到数据所对应对象 
         */  
        @Override  
        public Object getValueAt(int rowIndex, int columnIndex)  
        {  
            //return data[rowIndex][columnIndex];
        	if(columnIndex==17) {
        		return detailsData.elementAt(rowIndex)[23];
        	}
        	return detailsData.elementAt(rowIndex)[columnIndex];
        }  
  
        /** 
         * 得到指定列的数据类型 
         */  
        @Override  
        public Class<?> getColumnClass(int columnIndex)  
        {  
        	
        	return String.class;
        	
//        	if(detailsData.size() == 0){
//        		return String.class;
//        	}
//
//            return detailsData.elementAt(0)[columnIndex].getClass();
        	
        }  
  
        /** 
         * 指定设置数据单元是否可编辑.这里设置"姓名","学号"不可编辑 
         */  
        @Override  
        public boolean isCellEditable(int rowIndex, int columnIndex)  
        {  
            return false;
        }  
          
        /** 
         * 如果数据单元为可编辑，则将编辑后的值替换原来的值 
         */  
        @Override  
        public void setValueAt(Object aValue, int rowIndex, int columnIndex)  
        {  
            detailsData.elementAt(rowIndex)[columnIndex] = (String)aValue;  
            /*通知监听器数据单元数据已经改变*/  
            fireTableCellUpdated(rowIndex, columnIndex);  
        }  
        
        public void updateTable(){
        	fireTableDataChanged();
        }
        
  
    }  

}
